#include "tcpserver.h"
#include <QDebug>

TcpServer::TcpServer()
{
    tcpServer=new QTcpServer();
  //  QHostAddress::Any   QHostAddress::LocalHost
        if(!tcpServer->listen(QHostAddress::Any,2014))
        {  //监听本地主机的6666端口，如果出错就输出错误信息，并关闭
            qDebug() << tcpServer->errorString();
        //    close(0);
        }
     connect(tcpServer,SIGNAL(newConnection()),this,SLOT(sendMessage()));
     connect(tcpServer,SIGNAL(destroyed()),this,SLOT(showNoConnection()));
 //    connect(tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),

//              this,SLOT(displayError(QAbstractSocket::SocketError)));

     qDebug()<<"TCP Server is ready!";
}
void TcpServer::showNoConnection()
{
    sigTcpStause(-1);           //断开连接
//    qDebug()<<"no conn";
}
void TcpServer::displayError(QAbstractSocket::SocketError)
{
    qDebug() << tcpSocket->errorString(); //输出错误信息
}
void TcpServer::sendMessage()
{
    tcpSocket = tcpServer->nextPendingConnection();
    sigTcpStause(0);        //新的连接
    //我们获取已经建立的连接的子套接字
    connect(tcpSocket,SIGNAL(disconnected()),this,SLOT(showNoConnection()));
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(updateServerProgress()));

    //发送数据成功后，显示提示
    qDebug()<<"new tcp connection"<<tcpSocket->peerAddress()<<tcpSocket->peerPort();
}
void TcpServer::updateServerProgress()
{
        QByteArray block = tcpSocket->readAll();

        qDebug()<< block.toHex();

        char *ch;
        ch=block.data();
        QString str(ch);
        if (str.left(6)=="sanwei")
        {
            char flaga= ch[6] ;      //标志位
            char flagb= ch[7] ;      //标志位

            if ((flaga=='0')&&(flagb=='a'))          //误差测量参数设置
            {
                wcclSetup(ch);
            }
            else if((flaga=='0')&&(flagb=='1'))          //非同步误差测量
            {
                wcclSetup_f(ch + 8);
            }
            else if((flaga=='0')&&(flagb=='2'))
            {
                smvAllChannel(ch);
            }
            else if((flaga=='0')&&(flagb=='b'))          //对时守时测量参数设置
            {
                dsSetup(ch);
            }
            else if((flaga=='0')&&(flagb=='c'))          //9-2 谐波分析
            {
                xbSetup(ch);
            }
            else if((flaga=='0')&&(flagb=='d'))          //录波参数设置
            {
                lbSetup(ch);
            }
            else if((flaga=='0')&&(flagb=='e'))          //报文质量测试
            {
                muSetup(ch);
            }
            else if((flaga=='0')&&(flagb=='f'))          //模拟加量设置
            {
                mnSetup(ch);
            }
            else if((flaga=='0')&&(flagb=='g'))          //ft3加量设置
            {
                ft3Setup(ch);
            }
            else if((flaga=='0')&&(flagb=='0'))          //复位
            {
                reSet();
            }
        }
}

void TcpServer::wcclSetup(char *ch)
{
    qDebug()<<"Cmd from TCP: wcclSetup";
    m_iTbfs=ch[8]-'0';
    m_iLx=ch[9]-'0';
    char temp[10];
    for(int i=0;i<10;i++)
        temp[i]=ch[10+i];
    m_fEdyc=atof(temp);
    m_iEdycDw=ch[20]-'0';
    m_iJd=ch[21]-'0';
    m_iBzSelect=ch[22]-'0';
    for(int i=0;i<10;i++)
        temp[i]=ch[23+i];
    m_fBzDyz=atof(temp);
    m_iBcSelect=ch[33]-'0';
    m_iBcTd=(ch[34]-'0')*10+(ch[35]-'0') -1;
    m_iBcTdLx=ch[36]-'0';
    for(int i=0;i<10;i++)
        temp[i]=ch[37+i];
    m_fBcDyz=atof(temp);
    m_iCyfs=ch[47]-'0';
    if (m_iCyfs==1)
    {
        char tempa[17];
        for(int i=0;i<17;i++)
            tempa[i]=ch[48+i];
        QString str(tempa);
        m_sMac=str.left(17);

        qDebug()<<"m_sMac"<<m_sMac;
    }
    else
        m_sMac="";
    m_iInput=ch[65]-'0';

    emit sigTcpOrder(0);
}

void TcpServer::wcclSetup_f(char *ch)
{
    qDebug()<<"Cmd from TCP: wcclSetup_f";
    char temp[10];
    for(int i=0;i<10;i++)
        temp[i]=ch[i];
    m_fDelay = atof(temp);
    m_iLx=ch[10]-'0';
    for(int i=0;i<10;i++)
        temp[i]=ch[11+i];
    m_fEdyc=atof(temp);
    m_iEdycDw=ch[21]-'0';
    m_iJd=ch[22]-'0';
    m_iBzSelect=ch[23]-'0';
    for(int i=0;i<10;i++)
        temp[i]=ch[24+i];
    m_fBzDyz=atof(temp);
    m_iBcSelect=ch[34]-'0'; //61850=5, ft3=6
    m_iBcTd=(ch[35]-'0')*10+(ch[36]-'0') -1;
    m_iBcTdLx=ch[37]-'0';
    for(int i=0;i<10;i++)
        temp[i]=ch[38+i];
    m_fBcDyz=atof(temp);
    m_iCyfs=ch[48]-'0';
    if (m_iCyfs==2)
    {
        char tempa[17];
        for(int i=0;i<17;i++)
            tempa[i]=ch[49+i];
        QString str(tempa);
        m_sMac=str.left(17);
    }
    else
        m_sMac="";
    m_iInput=ch[66]-'0';

    emit sigTcpOrder(1);
}

void TcpServer::reSet()        //复位
{
    qDebug()<<"tcpCmd() reset!";

    emit sigTcpOrder(10);
}

void TcpServer::smvAllChannel( char *ch)
{
    m_iCurrentTd = (ch[8]-'0')*10 + ch[9]-'0';

    qDebug()<<"smvAllChannel"<<m_iCurrentTd;

    emit sigTcpOrder(14);
}

void TcpServer::ft3Setup(char *ch)
{
    m_iFt3Lx=ch[8]-'0';
    m_iFt3Pl=ch[9]-'0';
    m_iFt3Btl=ch[10]-'0';
    char temp[2];
    for(int i=0;i<2;i++)
        temp[i]=ch[11+i];
    m_sLNName=QString(QLatin1String(temp));
    char tempa[4];
    for(int i=0;i<4;i++)
        tempa[i]=ch[13+i];
    m_sLDName=QString(QLatin1String(tempa));
    for(int i=0;i<2;i++)
        temp[i]=ch[15+i];
    m_sDSNName=QString(QLatin1String(temp));
    char tempb[10];
    for(int i=0;i<10;i++)
        tempb[i]=ch[17+i];
    m_iEddl=atoi(tempb);
    for(int i=0;i<10;i++)
        tempb[i]=ch[27+i];
    m_iEdzxdl=atoi(tempb);
    for(int i=0;i<10;i++)
        tempb[i]=ch[37+i];
    m_iEddy=atoi(tempb);
    for(int i=0;i<4;i++)
        tempa[i]=ch[47+i];
    m_sStause1=QString(QLatin1String(tempa));
    for(int i=0;i<4;i++)
        tempa[i]=ch[51+i];
    m_sStause2=QString(QLatin1String(tempa));
    for(int i=0;i<2;i++)
        temp[i]=ch[55+i];
    m_iTdNum=atoi(temp);
    for(int j=0;j<m_iTdNum;j++)
    {
        for(int i=0;i<10;i++)
            tempb[i]=ch[57+i+j*15];
        m_sFz[j]=QString(QLatin1String(tempb));
        char tempc[5];
        for(int i=0;i<5;i++)
            tempc[i]=ch[67+i+j*15];
        m_sXw[j]=QString(QLatin1String(tempc));
    }
    emit sigTcpOrder(13);            //ft3加量参数
}
void TcpServer::dsSetup(char *ch)
{
    m_iCslx=ch[8] - '0';

    m_iBcsz=ch[9] - '0';

    m_iCsTime=ch[10] - '0';

    qDebug()<<"m_iCslx"<<m_iCslx<<m_iBcsz<<m_iCsTime;

    emit sigTcpOrder(2);            //对时守时测量参数，0b
}

void TcpServer::muSetup(char *ch)
{
//    m_iMuInput=ch[8]-'0';
    m_iMuTime=ch[8]-'0';
    emit sigTcpOrder(11);            //报文质量，0e
}

void TcpServer::xbSetup(char *ch)
{
    char temp[2];
    for(int i=0;i<2;i++)
        temp[i]=ch[8+i];
    m_iTdh=atoi(temp);
    for(int i=0;i<2;i++)
        temp[i]=ch[10+i];
    m_iXbcs=atoi(temp);
    emit sigTcpOrder(4);            //谐波参数，0c
}

void TcpServer::lbSetup(char *ch)
{
    m_iLbTime=ch[8]-'0';
    emit sigTcpOrder(6);            //录波参数,0d
}

void TcpServer::mnSetup(char *ch)
{
    char temp[10];
    for(int i=0; i<10; i++) temp[i]=ch[8+i];
    m_fXdyz=atoi(temp);

    char tempa[10];
    for(int i=0; i<10; i++) tempa[i]=ch[18+i];
    m_fBfd=atof(tempa);

    haveHarmonic = ch[28] - '0';

    char hTemp[2];
    hTemp[0] = ch[29];
    hTemp[1] = ch[30];
    h3 = atof(hTemp);

    hTemp[0] = ch[31];
    hTemp[1] = ch[32];
    h5 = atof(hTemp);

    hTemp[0] = ch[33];
    hTemp[1] = ch[34];
    h7 = atof(hTemp);

    hTemp[0] = ch[35];
    hTemp[1] = ch[36];
    h9 = atof(hTemp);

    hTemp[0] = ch[37];
    hTemp[1] = ch[38];
    h11 = atof(hTemp);

    emit sigTcpOrder(12);            //模拟加量参数,0f

    TcpSend("3a:ok");
}

void TcpServer::TcpSend(QString s)
{
    s="sanwei:"+s+"\r\n";

    QByteArray datagram = s.toLatin1();
 //   const char *send=datagram.data();
 //   qint64 len=datagram.size();
    tcpSocket->write(datagram);
}

void TcpServer::TcpSendFile(QString sfile)
{
    loadSize = 4*1024;
    totalBytes = 0;
    bytesWritten = 0;
    bytesToWrite = 0;
    localFile=new QFile(sfile);
    if(!localFile->open(QFile::ReadOnly))
    {
        qDebug() << "open file error!";
        return;
    }
    totalBytes = localFile->size();     //文件总大小
    QDataStream sendOut(&outBlock,QIODevice::WriteOnly);
/*
#if defined(__arm__)
    sendOut.setVersion(QDataStream::Qt_4_8);
#else
    sendOut.setVersion(QDataStream::Qt_4_7);
#endif
*/
    QString currentFileName = sfile.right(sfile.size() - sfile.lastIndexOf('/')-1);
    sendOut << qint64(0) << qint64(0) << currentFileName;   //依次写入总大小信息空间，文件名大小信息空间，文件名
    totalBytes += outBlock.size();                  //这里的总大小是文件名大小等信息和实际文件大小的总和
    sendOut.device()->seek(0);
    sendOut<<totalBytes<<qint64((outBlock.size() - sizeof(qint64)*2));      //返回outBolock的开始，用实际的大小信息代替两个qint64(0)空间
    bytesToWrite = totalBytes - tcpSocket->write(outBlock);     //发送完头数据后剩余数据的大小
    outBlock.resize(0);
    connect(tcpSocket,SIGNAL(bytesWritten(qint64)),this,SLOT(updateSendFile(qint64)));
}

void TcpServer::updateSendFile(qint64 numBytes) //更新进度条，实现文件的传送
{
    bytesWritten += (int)numBytes;  //已经发送数据的大小
    if(bytesToWrite > 0) //如果已经发送了数据
    {
        outBlock = localFile->read(qMin(bytesToWrite,loadSize));//每次发送loadSize大小的数据，这里设置为4KB，如果剩余的数据不足4KB，
        bytesToWrite -= (int)tcpSocket->write(outBlock);//就发送剩余数据的大小//发送完一次数据后还剩余数据的大小
        outBlock.resize(0);    //清空发送缓冲区
    }
    else
    {
        localFile->close(); //如果没有发送任何数据，则关闭文件
    }
    if(bytesWritten == totalBytes) //发送完毕
    {
         qDebug()<<tr("文件传输成功！");
         localFile->close();
    }
}
